package org.bdgame.common;

import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.bdgame.blog.Blog;
import org.bdgame.blog.BlogController;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.c3p0.C3p0Plugin;

/**
 * API引导式配置
 */
public class DemoConfig extends JFinalConfig {
	
	public static String host;
	public static String port;
	public static String user;
	public static String dbname;
	public static String passwd;
	String url;
	private Logger loger;
	
	
	
	/**
	 * 配置常量
	 */
	public void configConstant(Constants me) {
		// 加载少量必要配置，随后可用getProperty(...)获取值
		loger=Logger.getLogger(this.getClass()); 
		
		Map<String,String> envs=System.getenv();
		Iterator<String> keys=envs.keySet().iterator();
		String key=null;
		String cNum=null;
		int index=-1;
		while(keys.hasNext()){
			key=keys.next();
			if((index=key.indexOf("MYSQL"))!=-1){
				cNum=key.substring(index+5, key.indexOf("_", index));
			}
		}
		host=System.getenv("MOPAAS_MYSQL"+cNum+"_HOSTNAME");
		port=System.getenv("MOPAAS_MYSQL"+cNum+"_PORT");
		user=System.getenv("MOPAAS_MYSQL"+cNum+"_USERNAME");
		dbname=System.getenv("MOPAAS_MYSQL"+cNum+"_NAME");
		passwd=System.getenv("MOPAAS_MYSQL"+cNum+"_PASSWORD");
		
		url="jdbc:mysql://"+host+":"+port+"/"+dbname;
		loger.info("jdbcurl:"+url);
		loger.debug("cNum:"+cNum);
		me.setDevMode(true);
	}
	
	/**
	 * 配置路由
	 */
	public void configRoute(Routes me) {
		me.add("/", CommonController.class);
		me.add("/blog", BlogController.class);
	}
	
	/**
	 * 配置插件
	 */
	public void configPlugin(Plugins me) {
		// 配置C3p0数据库连接池插件
		C3p0Plugin c3p0Plugin = new C3p0Plugin(url, user, passwd.trim());
		me.add(c3p0Plugin);
		
		
		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
		me.add(arp);
		Db.update("CREATE TABLE IF NOT EXISTS `blog`(" +
					" `id` int(11) NOT NULL auto_increment," +
					" `title` varchar(200) NOT NULL," +
					" `content` mediumtext NOT NULL," +
					"PRIMARY KEY  (`id`)" +
					") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
		Db.update("INSERT INTO `blog`(title,content) VALUES ( 'JFinal Demo Title here', 'JFinal Demo Content here');");
		loger.info("db create");
		arp.addMapping("blog", Blog.class);	// 映射blog 表到 Blog模型
	}
	
	/**
	 * 配置全局拦截器
	 */
	public void configInterceptor(Interceptors me) {
		
	}
	
	/**
	 * 配置处理器
	 */
	public void configHandler(Handlers me) {
		
	}
	
}
